Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
Use string "array[n]" as variable

I dont know how to really explain this, but here my problem.

i have a string "myKey[2]" and i want to

const values = {
 "myKey": ["hey", "oh"],
 "b": ["something"]
};

const str = "myKey[2]";

My question is : how to get "oh" with a string as a variable name + is there something in js who can read "myarray.key" as variable too without apply many regex and function ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

As the indexing for the array starts from zero, accessing "myKey[2]" will give you undefined.Assuming you want to take the second element from the array,we can do

const values = {
 "myKey": ["hey", "oh"],
 "b": ["something"]
};

const str = "myKey[1]";

const result=values[str.slice(0, str.indexOf('['))][
  Number(str.slice(str.indexOf('[') + 1, str.indexOf(']')))
];

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your string should be

const str = values.myKey[1];

or if your key has dashes and such

const str = values['myKey'][1];

Keep in mind that the right index in this case is 1, not 2 as the index numbering in arrays starts from 0 and not 1.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda